import numpy as np
import requests
import time
from datetime import datetime

# ------------------- 接口配置 -------------------
URL = "http://127.0.0.1:8000/ecg_upload"
DEVICE_ID = "ECG1"         # 对应数据库中已存在的设备 ID
POINTS_PER_SECOND = 500        # 采样率 500Hz
UPLOAD_INTERVAL = 2            # 每次上传 2 秒数据
DURATION_SEC = 60              # 模拟 60 秒
FREQUENCY = 1.0                # 正弦波频率 1Hz
AMPLITUDE = 1.0                # 振幅

# ------------------- 生成正弦波 -------------------
t = np.linspace(0, DURATION_SEC, int(POINTS_PER_SECOND * DURATION_SEC), endpoint=False)
y = AMPLITUDE * np.sin(2 * np.pi * FREQUENCY * t)

print(f"✅ 正弦波已生成：频率 {FREQUENCY}Hz，采样率 {POINTS_PER_SECOND}Hz，总点数 {len(y)}")

# ------------------- 模拟上传 -------------------
for sec in range(0, DURATION_SEC, UPLOAD_INTERVAL):
    start = sec * POINTS_PER_SECOND
    end = (sec + UPLOAD_INTERVAL) * POINTS_PER_SECOND
    batch = y[start:end]
    batch_timestamps = t[start:end]

    data_str = ",".join(map(lambda x: f"{x:.4f}", batch))
    timestamps_str = ",".join(map(lambda x: f"{x:.4f}", batch_timestamps))

    payload = {
        "device_id": DEVICE_ID,
        "data": data_str,
        "timestamps": timestamps_str
    }

    try:
        res = requests.post(URL, data=payload, timeout=5)
        status = res.status_code
        if status == 200:
            print(f"[{datetime.now().strftime('%H:%M:%S')}] 上传成功：{len(batch)} 点")
        else:
            print(f"[{datetime.now().strftime('%H:%M:%S')}] 上传失败({status})：{res.text}")
    except Exception as e:
        print(f"[{datetime.now().strftime('%H:%M:%S')}] 上传错误：{e}")

    time.sleep(UPLOAD_INTERVAL)

print("✅ 测试结束，正弦波数据已全部上传。")
